//使用自调用函数关住作用域
(function(){
    var ps = "absolute";
    //蛇对象的构造函数
    function Snake (option){
        option = option instanceof Object ? option : {};
        //避免传入的参数类型不对
        this.width = option.width || 20;
        this.height = option.height || 20;
        //设置蛇身的数据
        this.body = [
            {x : 3, y : 2, color : "red"},
            {x : 2, y : 2, color : "blue"},
            {x : 1, y : 2, color : "blue"}
        ];
        //设置蛇移动的方向
        this.direction = "right";
        this.elements = [];
    }
    

    Snake.prototype.render = function(map){
    //
    for(var i = 0, len = this.body.length; i < len; i++){

    var piece = this.body[i];
    //创建新元素
    var ele = document.createElement("div");
    // 添加样式
    ele.style.width = this.width + "px";
    ele.style.height = this.height + "px";
    ele.style.left = piece.x * this.width + "px";
    ele.style.top = piece.y * this.height + "px";
    ele.style.backgroundColor = piece.color;
    ele.style.position = ps;
    //渲染到指定的父级内部
    map.appendChild(ele);
    this.elements.push(ele);
    }


    //添加蛇的运动方法
    Snake.prototype.move = function(){
        //蛇身的每一节都要变成上一节的位置
        //循环需要从最后一项开始，为了避免前面的数据提前发生变化
        for(var i =this.body.length -1; i>0; i--){
            this.body[i].x = this.body[i-1].x;
            this.body[i].y = this.body[i-1].y;
        }
        var head = this.body[0];

        switch(this.direction){
            case "right":
                head.x +=1;
                break;
            case "left":
                head.x -=1;
                break;
            case "top":
                head.y +=1;
                break;
            case "bottom":
                head.y -=1;
                break;
        }
    }


    //删除蛇的方法
    Snake.prototype.remove = function(map){

        for(var i = this.elements.length - 1; i>=0; i--){
            map.removeChild(this.elements[i]);
        }
        //清空数组
        this.elements = [];
    }
    };

    //通过window暴露构造函数
    window.Snake = Snake;
   
})();

